<?
/**
 * Simple Templater!
 * 
 * @package potLite.core.templater
 * @author asmhack
 * @version since begin
 * @license GPL
 * @copyright Serhiy Zaporozhets'
 *
 */
class Templater {
	
	private function __construct() {
	}
	private function __clone() {
	}
	
	public static function setTemplatePath($pathName='') {
		Session::putSystemValue ( 'defTmpl', $pathName, false );
	}
	
	public static function loadTemplate($pathName = '') {
		$c = ConfigReader::getInstance ();
		if (trim ( $pathName ) != '')
			return self::get ( $pathName );
		else {
			$c = ConfigReader::getInstance ();
			self::setTemplatePath ( $c->getTemplate () );
			return self::get ( $c->getTemplate () );
		}
	}
	
	public static function getTemplatePath() {
		return Session::getSystemValue ( 'defTmpl', false );
	}
	/**
	 * @var $params - array of params.
	 * /
   public static function get($pathName, $params = array()) {
      if (file_exists ( $pathName )) {
         if (count ( $params ) > 0)
            extract ( $params, EXTR_REFS );
         ob_start ();
         include_once ($pathName);
         $ret = ob_get_contents ();
         ob_end_clean ();
         chdir ( dirname ( $_SERVER ['SCRIPT_FILENAME'] ) );
         return strval ( $ret );
      } else
         return '';
	 */
	public static function getOnlyPHP($fileName, $params = array()) {
		if (file_exists ( $fileName )) {
			if (count ( $params ) > 0)
				extract ( $params, EXTR_REFS );
			ob_start ();
			include_once $fileName;
			$ret = ob_get_contents ();
			ob_end_clean ();
			//chdir ( dirname ( $_SERVER ['SCRIPT_FILENAME'] ) );
			return $ret;
		}
		return null;
	}
	
	public static function get($fileName, $params = array()) {
		$ret=self::getOnlyPHP($fileName,$params);
		if ($ret!=null) {
			$package = ConfigReader::getInstance ();
			$tagLibs = $package->getTagLibs ();
			foreach ( $tagLibs as $prefix => $tagLibColl ) { // for each tag lib
				foreach ( $tagLibColl as $className => $fileName ) { // for each tags in current tag lib
					if (file_exists ( $fileName ))
						require_once $fileName;
					if (! class_exists ( $className ))
						die ( '<h1>' . $className . '</h1> not found!' ); # TODO: refactor to throwing Exception....
					
					$ai = new AnnotationInvoker ( $className );
					
					$fileContent = $ai->regexp ( $ret, $prefix, $params );
				}
			}
			return $fileContent;
		} else
			return '';
	}
	
	/**
	 * for maybe older version support.
	 * @param $tplUrl
	 * @param $params
	 * @return unknown_type
	 */
	public static function put($tplUrl, $params = array()) {
		return self::get ( $tplUrl, $params );
	}
	
	public static function returnFile($path) {
		ob_start ();
		include_once ($path);
		$ret = ob_get_contents ();
		ob_end_clean ();
		chdir ( dirname ( $_SERVER ['SCRIPT_FILENAME'] ) );
		return $ret;
	}
}
?>
